package servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import xmlService.ListaDePreciosXmlService;
import beans.ListaDePreciosBean;
import controller.BusinessDelegate;

public class IngresarListaDePrecios extends HttpServlet{

	
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		BusinessDelegate bd = BusinessDelegate.getInstancia();
		
		ListaDePreciosBean listaDePrecios;// = new IngresarSolicitud.java();
		/*String entidadCuil = req.getParameter("EntidadCuil");
		
		EntidadBean proveedor = null;
		if(!StringUtils.isEmpty(entidadCuil)){
				proveedor = bd.getProveedor(entidadCuil);
		}else{
			//ERROR
		}*/
		if(req.getAttribute("ERROR") != null)
			req.removeAttribute("ERROR");
		if(req.getAttribute("LISTAITEMS") != null)
			req.removeAttribute("LISTAITEMS");

		String opcion = "";
		if(req.getParameter("opcion") != null)
			opcion = req.getParameter("opcion");

		if(ServletFileUpload.isMultipartContent(req) && "".equalsIgnoreCase(opcion)){
			try {
				ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
				List<FileItem> fileItemsList = servletFileUpload.parseRequest(req);
				if(!fileItemsList.isEmpty()){
					for(FileItem fileItem: fileItemsList){
						if(fileItem.getFieldName().equalsIgnoreCase("fileArchivo")){
							FileItem archivo = fileItem;
							listaDePrecios = ListaDePreciosXmlService.cargarListaDePrecios(archivo.getInputStream());
							bd.registrarListaDePrecios(listaDePrecios);
						}
					}
				}
			} catch (Exception e) {
				req.setAttribute("error", "Ocurrio un error registrando la lista de precios. \n " +e.getMessage());
			}
			RequestDispatcher rd = getServletContext().getRequestDispatcher("/ingresarListaDePrecios.jsp");
			rd.forward(req, resp);
		}
	}

	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}


}
